// 'use strict';
const config = {
	client_id: 'xxx',
	client_secret: 'xxx',
	redirect_uri: 'http://localhost:8080'
}
const userModels = ['_id', 'id', 'name', 'avatar_url', 'email', 'blog', 'weibo', 'html_url', 'bio', 'create_time',
	'update_time', 'stared', 'followers', 'following', 'followers_url', 'following_url',
	'starred_url', 'admin', 'token'
]
// 数据库连接
const db = uniCloud.database();
// 数据库指令
const dbCmd = db.command;
const user = {
	async login(param) { //用户登录
		let res = null
		let {
			client_id,
			client_secret,
			redirect_uri
		} = config
		if (param.code) {
			res = await user['getToken'](param.code, client_id, client_secret, redirect_uri)
			let token = null
			if (!res) { //code过期
				return {
					code: 401,
					msg: '用户令牌过期，请重新登录',
					data: ''
				}
			} else {
				token = res.data
			}
			// //获取gitee用户信息
			let userInfo = await user['getUserInfo'](res.data.access_token)
			// 查询用户是否存在 Y:直接返回用户数据 N:注册用户
			let {
				affectedDocs,
				data
			} = await user['findUserById'](userInfo.data.id)
			if (affectedDocs === 1) {
				let updated = await user['updateUser'](data[0]._id, {
					token,
					userInfo: userInfo.data
				})
				return {
					code: 200,
					msg: '登录成功',
					data: {
						token: token.access_token,
						userInfo: data[0]
					}
				}
			} else {
				// 构建用户信息对象
				let now = new Date().getTime()
				let userData = {
					id: userInfo.data.id,
					name: userInfo.data.name,
					avatar_url: userInfo.data.avatar_url,
					email: userInfo.data.email,
					blog: userInfo.data.blog,
					weibo: userInfo.data.weibo,
					html_url: userInfo.data.html_url,
					bio: userInfo.data.bio,
					create_time: now,
					update_time: now,
					stared: userInfo.data.stared,
					followers: userInfo.data.followers,
					following: userInfo.data.following,
					followers_url: userInfo.data.followers_url,
					following_url: userInfo.data.following_url,
					starred_url: userInfo.data.starred_url,
					admin: false,
					token
				}
				// 插入用户信息
				let {
					id
				} = await db.collection('users').add(userData)
				let {
					affectedDocs,
					data
				} = await user['findUserById'](userInfo.data.id, filed)
				if (affectedDocs === 1 || data.length === 1) {
					return {
						code: 200,
						msg: '登录成功',
						data: {
							token: token.access_token,
							userInfo: data[0]
						}
					}
				}
			}
		}
	},
	async updateUserInfo() { //同步更新gitee用户信息
		//todo
	},
	async updateUser(id, param) { // 更新
		let userData = {}
		let userKeys = ['name', 'avatar_url', 'email', 'blog', 'weibo', 'html_url', 'bio', 'stared',
			'followers', 'following', 'followers_url', 'following_url',
			'starred_url', 'token'
		]
		userKeys.forEach((item) => {
			if (item === 'token') {
				userData['token'] = param.token
			}
			userData[item] = param.userInfo[item]
		})
		let res = await db.collection('users').doc(id).update(userData)
		return res.updated ? {
			code: 200,
			msg: '设置成功',
			data: res
		} : {
			code: 400,
			msg: '设置失败',
			data: res
		}
	},
	async findUserById(id) { // 查询
		let fields = {}
		userModels.forEach((item, index) => {
			fields[item] = true
		})
		// fields['name'] = false
		// console.log(fields)
		return await db.collection('users').where({
			id: id // 匹配id
		}).field(fields).get()
	},
	
	async getUserInfo(token) {
		let res = await uniCloud.httpclient.request('https://gitee.com/api/v5/user', {
			method: 'GET',
			data: {
				access_token: token
			},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' // 指定返回值为json格式，自动进行parse
		})
		return res
	},
	async findToken(token) {
		return await db.collection('users').where({
			'token.access_token': dbCmd.eq(token)
		}).get()
	},
	async checkToken(param) {
		// 与数据库中的token匹配
		let res = await user['findToken'](param.token)
		let isOver = true
		let newToken = ''
		let now = new Date().getTime()
		if (res.data.length) { //token是否24小时过期
			isOver = 1000 * (res.data[0].token.created_at + 86400) < now ? true : false
		} else {
			return {
				code: 401,
				msg: '用户令牌过期，请重新登录',
				data: ''
			}
		}
		if (isOver) { //超时
			newToken = await user['refreshToken'](res.data[0].token.refresh_token)
			if (newToken.status === 200) { // 更新数据库中的token
				await user['updateUser'](res.data[0]._id, {
					token: newToken.data,
					userInfo: res.data[0]
				})
				return {
					code: 200,
					msg: '登录成功',
					data: {
						token: newToken.data.access_token,
						userInfo: res.data[0]
					}
				}
			} else {
				return {
					code: 401,
					msg: '用户令牌过期，请重新登录',
					data: {}
				}
			}
		} else {
			return {
				code: 200,
				msg: '自动登录成功',
				data: {
					token: param.token,
					userInfo: res.data[0]
				}
			}
		}
	},
	async getToken(code, client_id, client_secret, redirect_uri) {
		let res = await uniCloud.httpclient.request('https://gitee.com/oauth/token', {
			method: 'POST',
			data: {
				grant_type: 'authorization_code',
				code,
				client_id,
				client_secret,
				redirect_uri
			},
			contentType: 'json',
			dataType: 'json'
		})
		if (res.status === 401) {
			return false
		} else {
			return res
		}

	},
	async refreshToken(refresh_token) {
		return await uniCloud.httpclient.request('https://gitee.com/oauth/token', {
			method: 'POST',
			data: {
				grant_type: 'refresh_token',
				refresh_token
			},
			contentType: 'json',
			dataType: 'json'
		})
	}
}
async function main(args) {
	return await user[args.opt](args)
}

exports.main = main;
